﻿using System;
using System.Collections.Generic;
using System.Net;
using System.ServiceModel;
using Microsoft.Practices.Unity;
using SpectrumAnalyser.Common.Hosting;
using SpectrumAnalyser.Config.Client;
using SpectrumAnalyser.ModelObjects.Enum;

namespace SpectrumAnalyser.Hosts.Common
{
    public class ServiceHostBase
    {
        private readonly IUnityContainer _unityContainer;
        private ServiceHost _host;
        private readonly ServiceHostBoostrapperBase _hostBoostrapperBase;

        public ServiceHostBase(IUnityContainer unityContainer)
        {
            this._unityContainer = unityContainer;
            this._hostBoostrapperBase = unityContainer.Resolve<ServiceHostBoostrapperBase>();
        }

        private void CreateHost(Type contractType, Type serviceType)
        {
            var hostUri = WcfHelper.GetEndpointUri(UriScheme.Http, contractType);
            this._host = new UnityServiceHost(_unityContainer, serviceType, hostUri);

            _host.AddServiceEndpoint(contractType, WcfHelper.GetBinding(UriScheme.Http), "");

            this._host.Open();
        }

        public void Run(string[] args)
        {
            foreach (var serviceType in ServiceTypes())
            {
                CreateHost(serviceType.Key, serviceType.Value);
            }

            InitializeConfigService(args[0]);

            this._hostBoostrapperBase.Initialize();
        }

        private void InitializeConfigService(string configServiceUri)
        {
            _unityContainer.Resolve<ConfigClient>().Initialize(configServiceUri);
        }

        protected virtual IDictionary<Type, Type> ServiceTypes()
        {
            return new Dictionary<Type, Type>();
        } 
    }
}